<template>
  <view class="idcard-container">
    <!-- 标题 -->
    <!-- <view class="title">身份证识别</view> -->
    
    <!-- 示例图 -->
    <view class="example-container">
      <!-- <image class="example-image" src="/static/idcard_example.png" mode="aspectFit"></image> -->
      <text class="example-text">请将身份证置于取景框内</text>
    </view>
    
    <!-- 识别区域 - 动态切换相机和照片 -->
    <view class="scan-container">
      <!-- 相机组件，拍照前显示 -->
      <camera v-if="!photoPath" class="camera" device-position="back" flash="off" @error="cameraError"></camera>
      <!-- 照片组件，拍照后显示 -->
      <image v-else class="photo" :src="photoPath" mode="aspectFill"></image>
      <view class="scan-mask">
        <view class="scan-frame"></view>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="btn" @click="takePhoto">{{ photoPath ? '重新拍摄' : '拍照识别' }}</button>
      <button class="btn btn-upload" @click="uploadImage">上传图片</button>
      <!-- <button v-if="photoPath" class="btn btn-confirm" @click="recognizeIdCard">确认识别</button> -->
    </view>
  </view>
</template>

<script>
	import {
		useridcardmsg
	} from '@/api/user.js'
const global = getApp().globalData;
export default {
  data() {
    return {
		app: {
			global: global,
			name: global.appName,
			language: global.language
		},
      photoPath: '',
	  resultData: null,
	  cameraContext: null
    }
  },
  onLoad() {
    this.cameraContext = uni.createCameraContext(this);
    this.checkCameraPermission();
  },
  methods: {
    // 检查相机权限
    checkCameraPermission() {
      uni.authorize({
        scope: 'scope.camera',
        success: () => {
          console.log('已授权相机权限');
        },
        fail: () => {
          uni.showModal({
            title: '提示',
            content: '需要相机权限才能使用身份证识别功能',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting();
              }
            }
          });
        }
      });
    },
    
    // 拍照
    takePhoto() {
      if (this.photoPath) {
        // 如果已经有照片，点击则重新拍摄
        this.photoPath = '';
        this.resultData = null;
        return;
      }
      
      this.cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          // 保存照片路径，显示定格的照片
          this.photoPath = res.tempImagePath;
        },
        fail: (err) => {
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          });
          console.error('拍照失败:', err);
        }
      });
    },
    
    // 上传图片
    uploadImage() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          this.photoPath = res.tempFilePaths[0];
          this.recognizeIdCard();
        }
      });
    },
    
    // 识别身份证
    recognizeIdCard() {
      if (!this.photoPath) {
              uni.showToast({
                title: '请先拍照或上传图片',
                icon: 'none'
              });
              return;
            }
            
            uni.showLoading({
              title: '识别中...'
            });
            
            // 模拟识别过程
            setTimeout(() => {
              uni.hideLoading();
              console.log('111',this.photoPath)
			  const uploadTask = uni.uploadFile({
			  	url: 'https://mqzhian.cn:8088/common/upload', // 你的ThinkPHP服务器地址
			  	filePath: this.photoPath,
			  	name: 'file', // 这里根据服务器接收的字段来定义
			  	success: (uploadFileRes) => {
			  		const data = JSON.parse(uploadFileRes.data);
			  		console.log('上传成功', data);
					uni.hideLoading();
					const parsedData = {}
					parsedData.img = data.fileName
					console.log('parsedData',parsedData)
					// 返回上一页并携带数据
					this.returnWithData(parsedData);
			  	},
			  	fail: (error) => {
			  		console.error('上传失败', error);
			  		uni.showToast({
			  			title: '上传失败',
			  			icon: 'none',
			  		});
			  	}
			  });
            }, 1500);
    },
	
	// 返回上一页并携带数据
	    returnWithData(data) {
	      // 将数据转换为JSON字符串
	      const dataStr = encodeURIComponent(JSON.stringify(data));
	      
	      // 返回上一页并携带数据
	      uni.navigateBack({
	        delta: 1,
	        success: () => {
	          // 通过事件通道传递数据
	          const eventChannel = this.getOpenerEventChannel();
	          eventChannel.emit('idCardData', data);
	        },
	        fail: (err) => {
	          console.error('返回失败:', err);
	          // 如果返回失败，尝试使用其他方式传递数据
	          uni.setStorageSync('lastIdCardData', data);
	        }
	      });
	    },
    
    // 相机错误处理
    cameraError(e) {
      console.error('相机错误:', e);
      uni.showToast({
        title: '相机错误',
        icon: 'none'
      });
    }
  }
}
</script>

<style>
.idcard-container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.example-container {
  margin-bottom: 30rpx;
  text-align: center;
}

.example-image {
  width: 300rpx;
  height: 200rpx;
  border-radius: 10rpx;
}

.example-text {
  display: block;
  margin-top: 10rpx;
  color: #888;
  font-size: 24rpx;
}

.scan-container {
  position: relative;
  width: 100%;
  height: 400rpx;
  margin-bottom: 40rpx;
}

.camera, .photo {
  width: 100%;
  height: 100%;
}

.scan-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

/* .scan-frame {
  width: 80%;
  height: 60%;
  border: 4rpx solid #00ff00;
  border-radius: 20rpx;
} */

.action-buttons {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 40rpx;
  flex-wrap: wrap;
}

.btn {
  width: 45%;
  background-color: #007aff;
  color: white;
  border-radius: 50rpx;
  margin-bottom: 20rpx;
}

.btn-upload {
  background-color: #ff9500;
}

.btn-confirm {
  background-color: #34C759;
  width: 90%;
}

.result-container {
  width: 100%;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.result-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}

.result-item {
  display: flex;
  margin-bottom: 15rpx;
}

.label {
  width: 150rpx;
  color: #666;
}

.value {
  flex: 1;
  font-weight: bold;
}
</style>